<template>
  <div class="product-container">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="全部" name="all" />
      <el-tab-pane label="审核中" name="checking" />
      <el-tab-pane label="出售中" name="saling" />
      <el-tab-pane label="已下架" name="off" />
      <el-tab-pane label="库存预警" name="min_stock" />
      <el-tab-pane label="回收站" name="delete" />
    </el-tabs>
    <el-card>
      <!-- 商品头部 -->
      <div slot="header" class="header">
        <!-- 页面搜索组件 -->
        <PageSearch placeholder="商品名称" title="商品名称" :goods-params="goodsParams" :options="options" :select-show.sync="selectShow" @search="getGoodsList" @useReset="reset">
          <span class="title">商品分类</span>
          <el-select v-model="goodsParams.category_id" placeholder="请选择商品分类">
            <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </PageSearch>
        <!-- 页面工具 -->
        <el-row type="flex" justify="space-between" class="tools-wrap">
          <el-col>
            <el-button size="mini" type="primary" @click="openDialog('add')">新增商品</el-button>
            <el-button
              v-if="goodsParams.tab === 'delete'"
              size="mini"
              type="warning"
              @click="restoreFn(ids)"
            >恢复商品</el-button>
            <el-popconfirm
              v-if="goodsParams.tab === 'delete'"
              confirm-button-text="是"
              cancel-button-text="否"
              class="delete-wrap"
              title="是否要删除彻底删除选中？"
              @confirm="deleteFn(ids)"
            >
              <el-button slot="reference" size="mini" type="danger">彻底删除</el-button>
            </el-popconfirm>
            <el-popconfirm
              v-else
              confirm-button-text="是"
              cancel-button-text="否"
              class="delete-wrap"
              title="是否要删除批量删除选中？"
              @confirm="deleteFn(ids)"
            >
              <el-button slot="reference" size="mini" type="danger">批量删除</el-button>
            </el-popconfirm>
            <el-button
              v-if="goodsParams.tab === 'all' || goodsParams.tab === 'off'"
              size="mini"
              class="up"
              @click="changeStatusBtn(1)"
            >上架</el-button>
            <el-button
              v-if="goodsParams.tab === 'all' || goodsParams.tab === 'saling'"
              size="mini"
              class="down"
              @click="changeStatusBtn(0)"
            >下架</el-button>
          </el-col>
          <el-col>
            <el-tooltip class="item" effect="dark" content="点击刷新" placement="top" @click.native="reset()">
              <el-button class="refresh"><el-icon class="el-icon-refresh" /></el-button>
            </el-tooltip>
          </el-col>
        </el-row>

      </div>
      <!-- 商品详情 -->
      <el-table
        v-if="goodsList"
        ref="multipleTable"
        v-loading="loading"
        class="product-center"
        :data="goodsList"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="selectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="商品" width="290">
          <template slot-scope="{row}">
            <el-row class="info" type="flex">
              <el-col :span="7">
                <el-image :src="row.cover" fit="cover" style="width: 50px; height: 50px" />
              </el-col>
              <el-col>
                <div class="name">{{ row.title }}</div>
                <div class="price">
                  <span>￥{{ row.min_price }}</span>
                  <span>￥{{ row.min_oprice }}</span>
                </div>
                <div class="type">分类：{{ row.category ? row.category.name : '未分类' }}</div>
                <div class="time">创建时间：{{ row.create_time }}</div>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column width="70" align="center" prop="sale_count" label="实际销量" />
        <el-table-column width="70" align="center" label="商品状态">
          <template slot-scope="{row}">
            <span v-if="row.status === 1" class="up">上架</span>
            <span v-else class="down">仓库</span>
          </template>
        </el-table-column>
        <el-table-column width="100" align="center" label="审核状态">
          <template slot-scope="{row}">
            <template v-if="row.ischeck === 0">
              <div class="btn">
                <el-button size="mini" type="success" plain @click="auditFn(row, 1)">审核通过</el-button>
                <el-button size="mini" type="danger" plain @click="auditFn(row, 2)">审核拒绝</el-button>
              </div>
            </template>
            <template v-else>
              <span>{{ row.ischeck === 1 ? '通过' : '拒绝' }}</span>
            </template>
          </template>

        </el-table-column>
        <el-table-column width="70" align="center" prop="stock" label="总库存" />
        <el-table-column align="right" label="操作">
          <template v-if="goodsParams.tab !== 'delete'" slot-scope="{row}">
            <el-button type="text" size="mini" @click="openDialog('edit', row.id)">修改</el-button>
            <el-button type="text" size="mini" @click="skusProduct(row.id)">商品规格</el-button>
            <el-button type="text" size="mini" @click="bannerProduct">设置轮播图</el-button>
            <el-button type="text" size="mini" @click="infoProduct">商品详情</el-button>
            <el-popconfirm
              confirm-button-text="是"
              cancel-button-text="否"
              class="delete-wrap"
              title="是否要删除该商品？"
              @confirm="deleteFn(ids)"
            >
              <el-button slot="reference" size="mini" type="text" @click="selectionChange(row.id)">删除</el-button>
            </el-popconfirm>
          </template>
          <span v-else>暂无操作</span>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-row class="pagination" type="flex" justify="center">
        <el-pagination
          background
          layout="prev, pager, next"
          current-page.sync="pagination.page"
          :total="Math.ceil(pagination.totalCount)"
          @current-change="handleCurrentChange"
        />
      </el-row>
    </el-card>
    <!-- 新增编辑弹层 -->
    <AddEditProduct
      ref="addEditProduct"
      :ids="ids"
      :options="options"
      :dialog-state="dialogState"
      :add-edit-dialog-show.sync="addEditDialogShow"
      @addEditProduct="getGoodsList()"
    />

    <!-- 商品规格 -->
    <SkusProduct :id="currentId" :skus-dialog-show.sync="skusDialogShow" @addDialog="openDialog" />

    <!-- 商品轮播图 -->
    <BannerProduct :banner-dialog-show.sync="bannerDialogShow" />

    <!-- 商品详情 -->
    <InfoProduct :info-dialog-show.sync="infoDialogShow" />
  </div>
</template>

<script>
import { getGoodsList, deleteGoods, restoreGoods, destroyGoods, changeStatus, changeCheck } from '@/api/goods'
import AddEditProduct from './components/add-edit-product.vue'
import SkusProduct from './components/skus-product.vue'
import BannerProduct from './components/banner-product.vue'
import InfoProduct from './components/info-product.vue'
export default {
  name: 'Product',
  components: {
    AddEditProduct,
    SkusProduct,
    BannerProduct,
    InfoProduct
  },
  data() {
    return {
      activeName: 'all', // tab栏切换
      options: [], // 下拉菜单商品分类
      selectShow: false, // 控制分类下拉菜单显示隐藏

      addEditDialogShow: false, // 控制add/edit弹层显示
      dialogState: null, // 弹层名

      dialogImageUrl: '',
      pagination: {
        totalCount: null, // 总记录数
        page: 1 // 分页页码
      },
      // 列表数据
      goodsList: [],
      goodsParams: {
        page: 1,
        tab: 'all',
        limit: 10,
        category_id: null,
        title: null
      },
      ids: [],
      loading: false, // 加载
      goodsId: null, // 当前商品id

      currentId: null, // 当前选择的商品id
      // 商品规格
      skusDialogShow: false, // 弹层显示
      // 商品轮播图
      bannerDialogShow: false, // 弹层显示
      // 商品详情
      infoDialogShow: false // 弹层显示
    }
  },
  created() {
    this.getGoodsList()
  },
  methods: {
    // 获取商品列表方法
    async getGoodsList() {
      this.loading = true
      try {
        const { list, totalCount, cates } = await getGoodsList({
          page: this.goodsParams.page,
          tab: this.goodsParams.tab,
          limit: this.goodsParams.limit,
          title: this.goodsParams.title,
          category_id: this.goodsParams.category_id
        })
        this.options = cates
        this.goodsList = list
        this.pagination.totalCount = totalCount
      } catch (error) {
        console.log(error)
      }
      this.loading = false
    },
    // tab栏切换触发方法
    handleClick(tab) {
      if (this.goodsParams.tab === tab.name) return
      this.goodsParams.tab = tab.name
      this.getGoodsList()
    },
    // 删除商品方法
    async deleteFn(ids) {
      if (this.goodsParams.tab !== 'delete') {
        try {
          // 批量/单个删除
          if (this.ids.length === 0) {
            return this.$message.error('还没勾选商品')
          } else await deleteGoods(ids)
          this.$message.success('删除成功')
        } catch (error) {
          this.$message.error('删除失败')
          console.log(error)
        }
      } else {
        try {
          // 彻底删除
          await destroyGoods(ids)
          this.$message.success('删除成功')
        } catch (error) {
          this.$message.error('删除失败')
          console.log(error)
        }
      }
      this.getGoodsList()
    },

    // 恢复商品方法
    async restoreFn(ids) {
      try {
        await restoreGoods(ids)
        this.$message.success('商品已恢复')
        this.goodsParams.tab = 'delete'
        this.getGoodsList()
      } catch (error) {
        this.$message.success('恢复失败')
        console.log(error)
      }
    },
    // 上架下架方法
    async changeStatusBtn(status) {
      const ids = this.ids
      try {
        console.log()
        await changeStatus({ ids, status })
        if (status === 1) {
          this.$message.success('商品上架成功')
        } else {
          this.$message.success('商品下架成功')
        }
        this.getGoodsList()
      } catch (error) {
        if (status === 1) {
          this.$message.error('商品上架失败')
        } else {
          this.$message.error('商品下架失败')
        }
        console.log(error)
      }
    },
    // 新增/编辑打开弹层方法
    openDialog(value, id) {
      this.goodsId = id
      this.dialogState = value
      if (this.dialogState === 'edit') {
        // 编辑
        const data = this.goodsList.find(obj => obj.id === id)
        // 获取到编辑的数据并通过调用子组件的方法传递数据
        this.$refs.addEditProduct.setFormData(data, id)
      }
      this.addEditDialogShow = true
    },
    // 复选框change方法
    selectionChange(val) {
      if (typeof val === 'number') {
        this.ids.push(val)
      } else this.ids = val.map(obj => obj.id)
    },
    // 审核
    async auditFn(row, state) {
      const id = row.id
      const ischeck = state
      try {
        await changeCheck({ id, ischeck })
        // 从新获取数据
        this.getGoodsList()
        this.$message.success('修改审核状态成功')
      } catch (error) {
        console.log(error)
        this.$message.error('修改审核状态失败')
      }
    },
    // 分页方法
    handleCurrentChange(page) {
      // console.log(page)
      this.goodsParams.page = page
      this.getGoodsList() // 切换页码，调用获取数据
      document.documentElement.scrollTop = 0
    },
    // 重置方法
    reset() {
      this.goodsParams = {
        page: 1,
        tab: 'all',
        limit: 10,
        category_id: null,
        title: null
      }
      this.$nextTick(() => {
        this.getGoodsList()
      })
    },

    // 商品规格打开
    skusProduct(id) {
      this.currentId = id
      this.skusDialogShow = true
    },
    // 商品轮播图
    bannerProduct() {
      this.bannerDialogShow = true
    },
    // 商品详情
    infoProduct() {
      this.infoDialogShow = true
    }

  }
}
</script>

<style lang="scss" scoped>
.product-container {
  .header {
    .title {
      margin-right: 10px;
    }
  }
  .tools-wrap {
    .up,.down {
      margin-left: 10px;
    }
    .el-col-24 {
      width: unset;
    }
  }
  .product-center {
    .info {
      .price {
        span:last-child {
          padding-left: 5px;
          border-left: 1px solid #ccc;
          font-size: 12px;
        }

        span:first-child {
          padding-right: 5px;
          color: red;
          font-size: 16px;
        }
      }

      .type {
        font-size: 12px;
        color: #9ca3af;
      }

      .time {
        font-size: 12px;
        color: #9ca3af;
      }
    }

    .el-button--danger.is-plain {
      margin: 0;
      margin-top: 10px;
      width: 90px;
      height: 24px;
    }

    .el-button--success.is-plain {
      width: 90px;
      height: 24px;
    }

    .up {
      color: #13ce66;
      background: #e7faf0;
      border: 1px solid #a1ebc2;
      border-radius: 3px;
      font-size: 12px;
      padding: 1px 4px;
    }

    .down {
      background: #ffeded;
      border: 1px solid #ff4949;
      border-radius: 3px;
      color: #ff4949;
      font-size: 12px;
      padding: 1px 4px;
    }
  }

  .table {
    ::v-deep .el-image {
      width: 75px !important;
      height: 75px !important;
    }
  }

  .pagination {
    margin: 30px 0 10px 0;
  }

  // 弹层样式
  .dialog-wrap {
    ::v-deep .el-upload--picture-card {
      width: 100px;
      height: 100px;
    }
  }

  .delete-wrap {
    margin-left: 10px;
  }

  .refresh {
    border: none;
    background: none;
  }

}
</style>
